package pay.utils;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Map;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EncryptDecryptUtils {
	private static Logger logger = LoggerFactory
			.getLogger(EncryptDecryptUtils.class);

	private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";

	public static boolean checkToken(String token, String userId) {
		boolean t = false;
		String key=CacheConstants.VALIDATE_TOKEN + token;
		String cacheUserId = RedisCilent
				.getString(key);
		if(StringHelper.isNotEmpty(cacheUserId)){
			//logger.info("key的值存在");
			if (userId.equals(cacheUserId)) {
			//	logger.info("key的值与userId相同,返回true");
				t = true;
				RedisCilent.delKey(CacheConstants.VALIDATE_TOKEN + token);
			}
//			else{
//				logger.info("key的值与userId不同,返回false,cacheUserId={},userId={}",cacheUserId,userId);
//			}
		}
//		else{
//			logger.info("key的值不存在,返回false");
//		}
		return t;
	}
	
	
	
	public static boolean checkLogToken(String token, String userId){
		boolean t = false;
		if (RedisCilent
				.existsKey(CacheConstants.UserLog_Token + userId)) {			
			String cacheToken = RedisCilent
					.getString(CacheConstants.UserLog_Token + userId);
			if (token.equals(cacheToken)) {				 
				t=true;
			}
		}
		return t;
	}
	
	public static Boolean validateSignByMap(String apiSecret,
			Map<String, String> map) {
		try {
			SecretKeySpec secret = new SecretKeySpec(apiSecret.getBytes(),
					HMAC_SHA1_ALGORITHM);
			Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
			mac.init(secret);
			StringBuilder url = new StringBuilder();
			for (Map.Entry<String, String> entry : map.entrySet()) {
				if (!entry.getKey().equals("sign")) {
					url.append("&" + entry.getKey() + "=" + entry.getValue());

				}
			}
			byte[] hmac = mac.doFinal(url.toString().getBytes()); // UTF8
			logger.info("生成的url为：" + url);
			String sign = Base64.getEncoder().encodeToString(hmac);
			logger.info("入参sign为：" + map.get("sign"));
			logger.info("生成的sign为：" + sign);
			if (sign.equals(map.get("sign"))) {

				return true;
			} else {
				return false;
			}

		} catch (NoSuchAlgorithmException | InvalidKeyException e) {
			logger.error("validateSignByMap()异常");
			e.printStackTrace();
			return false;
		}
	}
}
